package com.snail.snailvr.transfer;

import com.snail.snailvr.R;
import com.snail.snailvr.VRApp;
import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.event.NewPcConnectEvent;
import com.snail.snailvr.model.ConnectPc;
import com.snail.snailvr.network.providers.downloads.DownloadManager;
import com.snail.snailvr.network.providers.downloads.DownloadHelper;
import com.snail.snailvr.utils.DatabaseUtils;
import com.snail.snailvr.utils.Extensions;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.ToastUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.functions.Action1;

/**
 * Wifi传输Server
 * Created by Administrator on 2016/1/22.
 */
public class CustomNanoHTTPD extends NanoHTTPD {
    private static final String ROOT_PATH = "html";
    private static final String FORM_NAME = "file";
    private static final String POST = "POST";
    private static final String GET = "GET";
    private static final String MIME_JAVASCRIPT = "text/javascript";
    private static final String MIME_CSS = "text/css";
    private static final String MIME_JPEG = "image/jpeg";
    private static final String MIME_PNG = "image/png";
    private static final String MIME_SVG = "image/svg+xml";
    private static final String MIME_JSON = "application/json";

    private NanoFileUpload uploader;

    public Response response = newFixedLengthResponse("");

    public String uri;

    public Method method;

    public Map<String, String> header;

    public Map<String, List<FileItem>> files;

    public CustomNanoHTTPD() {
        super(8192);
        uploader = new NanoFileUpload(new DiskFileItemFactory());
    }

    @Override
    public Response serve(IHTTPSession session) {
        //手机端显示PC名称
        newPcConnected(session);
        String mime_type = NanoHTTPD.MIME_HTML;
        Method method = session.getMethod();
        String uri = session.getUri();
        InputStream descriptor = null;
        if (method.toString().equalsIgnoreCase(GET)) {
            String path;
            if (uri.equals("/")) {
                path = "/index.html";
            } else {
                path = uri;
                try {
                    if (path.endsWith(".js")) {
                        mime_type = MIME_JAVASCRIPT;
                    } else if (path.endsWith(".css")) {
                        mime_type = MIME_CSS;
                    } else if (path.endsWith(".html")) {
                        mime_type = MIME_HTML;
                    } else if (path.endsWith(".jpeg")) {
                        mime_type = MIME_JPEG;
                    } else if (path.endsWith(".png")) {
                        mime_type = MIME_PNG;
                    } else if (path.endsWith(".jpg")) {
                        mime_type = MIME_JPEG;
                    } else if (path.endsWith(".svg")) {
                        mime_type = MIME_SVG;
                    } else if (path.endsWith(".json")) {
                        mime_type = MIME_JSON;
                    }
                } catch (Exception e) {
                    LogUtils.e("Exception=" + e.toString());
                }
            }
            try {
                descriptor = VRApp.getInstance().getAssets().open(ROOT_PATH + path);
            } catch (IOException ioe) {
                LogUtils.e("IOException=" + ioe.toString());
            }

        } else if (method.toString().equalsIgnoreCase(POST)) {
            try {

                files = uploader.parseParameterMap(session);
                if (files.get(FORM_NAME) != null && !files.get(FORM_NAME).isEmpty()) {
                    FileItem fileItem = files.get(FORM_NAME).get(0);
                    InputStream in = fileItem.getInputStream();
                    File downloadDir = DownloadManager.createDownloadDirIfNotExist();
                    if (downloadDir == null) {
                        ToastUtils.showToast(R.string.download_dir_not_found);
                    } else {
                        String fileName=renameIfNeed(fileItem.getName());
                        LogUtils.d("fileName="+fileName);
                        File file = new File(downloadDir, fileName);
                        FileOutputStream os = new FileOutputStream(file);
                        byte[] buffer = new byte[4 * 1024];
                        int length;
                        while ((length = (in.read(buffer))) > 0) {
                            os.write(buffer, 0, length);
                        }
                        in.close();
                        os.close();
                        //统一网页过滤
                        if (Extensions.isVideo(file.getAbsolutePath())) {
                            DownloadHelper.addNewTransferVideoTask(fileName, file.getAbsolutePath());
                        } else {
                            LogUtils.d("please transfer video");
                        }

                    }
                }
            } catch (Exception e) {
                LogUtils.e("Exception=" + e.toString());
                this.response.setStatus(Response.Status.INTERNAL_ERROR);
                e.printStackTrace();
            }
        }
        try {
            return new Response(Response.Status.OK, mime_type, descriptor, descriptor.available());
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.e("IOException=" + e.toString());
        }
        return null;
    }

    private void newPcConnected(IHTTPSession session) {
        String hostName = session.getRemoteHostName();
        BusProvider.getInstance().post(new NewPcConnectEvent(hostName));
        saveConnectPcToDatabase(hostName);

    }

    public void saveConnectPcToDatabase(String name) {
        Observable.just(name)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        ConnectPc connectPc = new ConnectPc(s);
                        connectPc.save();
                    }
                });
    }
    private String renameIfNeed(String fileName) {
        int current_file_index= DatabaseUtils.getFileIndex(fileName);
        LogUtils.d("file_index="+current_file_index);
        if (current_file_index == -1) {
            // 不需要重命名
            DatabaseUtils.saveFileIndex(fileName, 0);
        }
        else {
            ++current_file_index;
            DatabaseUtils.saveFileIndex(fileName, current_file_index);
            if(fileName.contains(".")) {
                String []splitArrays=fileName.split("\\.");
                fileName = splitArrays[0] + "-" + current_file_index+"."+splitArrays[1];
            }
        }
        return fileName;
    }

}
